<template>
  <div class="sticky-container">
    <div class="page-header">
      <div class="page-title">便签墙</div>
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加便签</el-button>
        <el-button type="info" icon="el-icon-back" @click="goToNote">返回笔记</el-button>
      </div>
    </div>

    <!-- 便签墙 -->
    <div class="sticky-wall">
      <div v-if="loading" class="loading-container">
        <el-spinner></el-spinner>
      </div>
      <el-empty v-else-if="stickyList.length === 0" description="暂无便签"></el-empty>
      <div v-else class="sticky-list">
        <div
          v-for="sticky in stickyList"
          :key="sticky.id"
          class="sticky-item"
          :style="{
            backgroundColor: sticky.color || '#FFEB3B',
            left: `${sticky.positionX || 0}px`,
            top: `${sticky.positionY || 0}px`,
            width: `${sticky.width || 200}px`,
            height: `${sticky.height || 200}px`,
            zIndex: sticky.isPinned ? 100 : 1
          }"
          @mousedown.stop="startDrag($event, sticky)"
        >
          <div class="sticky-header">
            <div class="sticky-actions">
              <i class="el-icon-edit" @click.stop="handleEdit(sticky)"></i>
              <i class="el-icon-delete" @click.stop="handleDelete(sticky)"></i>
              <i :class="sticky.isPinned ? 'el-icon-star-on' : 'el-icon-star-off'" @click.stop="togglePin(sticky)"></i>
            </div>
            <div class="sticky-resize" @mousedown.stop="startResize($event, sticky)"></div>
          </div>
          <div class="sticky-content" v-html="sticky.content"></div>
          <div class="sticky-footer">
            <span class="sticky-date">{{ sticky.updateTime | formatDate }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form ref="stickyForm" :model="stickyForm" :rules="stickyRules" label-width="80px">
        <el-form-item label="内容" prop="content">
          <el-input v-model="stickyForm.content" type="textarea" :rows="6" placeholder="请输入便签内容"></el-input>
        </el-form-item>
        <el-form-item label="颜色">
          <el-color-picker v-model="stickyForm.color" show-alpha></el-color-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getStickyList, addSticky, updateSticky, deleteSticky } from '@/api/sticky'

export default {
  name: 'Sticky',
  filters: {
    formatDate(value) {
      if (!value) return ''
      const date = new Date(value)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
  },
  data() {
    return {
      // 便签列表
      stickyList: [],
      // 加载状态
      loading: false,
      // 对话框
      dialogVisible: false,
      dialogTitle: '添加便签',
      submitLoading: false,
      // 表单
      stickyForm: {
        id: null,
        content: '',
        color: '#FFEB3B',
        positionX: 0,
        positionY: 0,
        width: 200,
        height: 200,
        isPinned: false
      },
      // 表单校验规则
      stickyRules: {
        content: [{ required: true, message: '请输入便签内容', trigger: 'blur' }]
      },
      // 拖拽相关
      isDragging: false,
      isResizing: false,
      currentSticky: null,
      startX: 0,
      startY: 0,
      startWidth: 0,
      startHeight: 0
    }
  },
  created() {
    this.fetchData()
  },
  mounted() {
    // 添加全局事件监听
    document.addEventListener('mousemove', this.onMouseMove)
    document.addEventListener('mouseup', this.onMouseUp)
  },
  beforeDestroy() {
    // 移除全局事件监听
    document.removeEventListener('mousemove', this.onMouseMove)
    document.removeEventListener('mouseup', this.onMouseUp)
  },
  methods: {
    // 获取便签列表
    fetchData() {
      this.loading = true
      getStickyList()
        .then(response => {
          this.stickyList = response.data
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 添加便签
    handleAdd() {
      this.dialogTitle = '添加便签'
      this.stickyForm = {
        id: null,
        content: '',
        color: '#FFEB3B',
        positionX: Math.floor(Math.random() * 300),
        positionY: Math.floor(Math.random() * 200),
        width: 200,
        height: 200,
        isPinned: false
      }
      this.dialogVisible = true
    },
    // 编辑便签
    handleEdit(sticky) {
      this.dialogTitle = '编辑便签'
      this.stickyForm = { ...sticky }
      this.dialogVisible = true
    },
    // 删除便签
    handleDelete(sticky) {
      this.$confirm('确认删除该便签吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteSticky(sticky.id)
            .then(() => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.fetchData()
            })
        })
        .catch(() => {})
    },
    // 切换固定状态
    togglePin(sticky) {
      const updatedSticky = { ...sticky, isPinned: !sticky.isPinned }
      updateSticky(updatedSticky)
        .then(() => {
          this.fetchData()
        })
    },
    // 提交表单
    submitForm() {
      this.$refs.stickyForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.stickyForm.id) {
            // 更新
            updateSticky(this.stickyForm)
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '更新成功'
                })
                this.dialogVisible = false
                this.fetchData()
                this.submitLoading = false
              })
              .catch(() => {
                this.submitLoading = false
              })
          } else {
            // 添加
            addSticky(this.stickyForm)
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.dialogVisible = false
                this.fetchData()
                this.submitLoading = false
              })
              .catch(() => {
                this.submitLoading = false
              })
          }
        }
      })
    },
    // 开始拖拽
    startDrag(event, sticky) {
      if (this.isResizing) return
      this.isDragging = true
      this.currentSticky = sticky
      this.startX = event.clientX
      this.startY = event.clientY
    },
    // 开始调整大小
    startResize(event, sticky) {
      this.isResizing = true
      this.currentSticky = sticky
      this.startX = event.clientX
      this.startY = event.clientY
      this.startWidth = sticky.width || 200
      this.startHeight = sticky.height || 200
      event.stopPropagation()
    },
    // 鼠标移动
    onMouseMove(event) {
      if (this.isDragging && this.currentSticky) {
        const dx = event.clientX - this.startX
        const dy = event.clientY - this.startY
        
        const updatedSticky = { ...this.currentSticky }
        updatedSticky.positionX = (updatedSticky.positionX || 0) + dx
        updatedSticky.positionY = (updatedSticky.positionY || 0) + dy
        
        // 更新视图上的位置
        const index = this.stickyList.findIndex(item => item.id === this.currentSticky.id)
        if (index !== -1) {
          this.$set(this.stickyList, index, updatedSticky)
        }
        
        this.startX = event.clientX
        this.startY = event.clientY
      } else if (this.isResizing && this.currentSticky) {
        const dx = event.clientX - this.startX
        const dy = event.clientY - this.startY
        
        const updatedSticky = { ...this.currentSticky }
        updatedSticky.width = Math.max(100, this.startWidth + dx)
        updatedSticky.height = Math.max(100, this.startHeight + dy)
        
        // 更新视图上的大小
        const index = this.stickyList.findIndex(item => item.id === this.currentSticky.id)
        if (index !== -1) {
          this.$set(this.stickyList, index, updatedSticky)
        }
      }
    },
    // 鼠标松开
    onMouseUp() {
      if ((this.isDragging || this.isResizing) && this.currentSticky) {
        // 保存位置或大小到服务器
        updateSticky(this.stickyList.find(item => item.id === this.currentSticky.id))
          .then(() => {
            // 不需要刷新，已经在视图上更新了
          })
      }
      this.isDragging = false
      this.isResizing = false
      this.currentSticky = null
    },
    // 返回笔记页面
    goToNote() {
      this.$router.push('/note')
    }
  }
}
</script>

<style lang="scss" scoped>
.sticky-container {
  position: relative;
  height: calc(100vh - 120px);
  overflow: hidden;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .sticky-wall {
    position: relative;
    height: calc(100% - 60px);
    background-color: #f5f5f5;
    border-radius: 4px;
    overflow: hidden;
    
    .loading-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
    }
    
    .sticky-list {
      position: relative;
      width: 100%;
      height: 100%;
    }
    
    .sticky-item {
      position: absolute;
      min-width: 150px;
      min-height: 150px;
      padding: 10px;
      border-radius: 2px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      display: flex;
      flex-direction: column;
      cursor: move;
      
      .sticky-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        
        .sticky-actions {
          i {
            margin-right: 8px;
            cursor: pointer;
            
            &:hover {
              color: #409EFF;
            }
          }
        }
        
        .sticky-resize {
          width: 10px;
          height: 10px;
          background-color: rgba(0, 0, 0, 0.1);
          border-radius: 50%;
          cursor: se-resize;
        }
      }
      
      .sticky-content {
        flex: 1;
        overflow-y: auto;
        word-break: break-word;
        line-height: 1.5;
      }
      
      .sticky-footer {
        margin-top: 10px;
        font-size: 12px;
        color: rgba(0, 0, 0, 0.5);
        text-align: right;
      }
    }
  }
}
</style> 